package com.yst.feign1.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 替换post的request
 * 方便多次获取requestbody
 */
@Slf4j
@Component
public class PostFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		log.info("PostFilter");
		//文件上传接口直接放行
		if (request instanceof HttpServletRequest && (
				((HttpServletRequest) request).getRequestURI().contains("file/upload")
//				|| ((HttpServletRequest) request).getRequestURI().contains("wx/portal")
		)) {
			chain.doFilter(request, response);
			return;
		}

		ServletRequest requestWrapper = null;
		if (request instanceof HttpServletRequest) {
			requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
		}
		if (requestWrapper == null) {
			chain.doFilter(request, response);
		} else {
			chain.doFilter(requestWrapper, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
}
